import type { IPSet, IPSetInfo, UserInfo } from "../../api/types";
import { ACTIONS } from "./constants";
import type { ActionTypes, RootState } from "./types";

const setUserInfo = (state: RootState, user: UserInfo | null) => {
  state.user = user;
  return state;
};

const logout = (state: RootState) => {
  state.user = null;
  return state;
};

const setIPSets = (state: RootState, ipsets: Record<string, IPSet> | null) => {
  state.ipsets = ipsets;
  return state;
};

const setIPSetInfo = (
  state: RootState,
  setname: string,
  info: IPSetInfo | null
) => {
  state.ipsetInfo = {
    ...state.ipsetInfo,
    [setname]: info as any,
  };
  return state;
};

export const reducer = (state: RootState, action: ActionTypes) => {
  const { type } = action;
  let clonedState = { ...state };
  switch (type) {
    case ACTIONS.SET_USERINFO:
      return setUserInfo(clonedState, action.user);
    case ACTIONS.LOGOUT:
      return logout(clonedState);
    case ACTIONS.SET_IPSETS:
      return setIPSets(clonedState, action.ipsets);
    case ACTIONS.SET_IPSETINFO:
      return setIPSetInfo(clonedState, action.setname, action.info);
    default:
      return state;
  }
};
